#import "XMLParser.h"

@implementation XMLParser

static XMLParser *sharedInstance = nil;

//싱글톤 적용
+ (XMLParser *) sharedInstance
{
    if(!sharedInstance) {
		sharedInstance = [[self alloc] init];
    }
    return sharedInstance;
}

+ (void) deallocInstance
{
    if(sharedInstance) {
        [sharedInstance release];
        sharedInstance = nil;
    }
}

//파싱한 결과의 최상위 루트노드를 리턴함
- (TreeNode *) parse: (NSXMLParser *) parser
{
	stack = [NSMutableArray array];
	
	TreeNode *root = [TreeNode treeNode];
	root.parent = nil;
	root.leafvalue = nil;
	root.children = [NSMutableArray array];
	
	[stack addObject:root];
	
	[parser setDelegate:self];
	[parser parse];
    [parser release];
    
	// pop down to real root
	TreeNode *realroot = [[root children] lastObject];
	root.children = nil;
	root.parent = nil;
	root.leafvalue = nil;
	root.key = nil;
	
	realroot.parent = nil;
	return realroot;
}


- (TreeNode *)parseXMLFromURL: (NSURL *) url
{
	TreeNode *results;
	NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    NSXMLParser *parser = [[NSXMLParser alloc] initWithContentsOfURL:url];
	results = [self parse:parser];
	[pool drain];
	return results;
}

- (TreeNode *)parseXMLFromData: (NSData *) data
{
	TreeNode *results;
	NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data];
	results = [self parse:parser];
	[pool drain];
	return results;
}

//Element의 시작
//chidren(MutableArray)의 원소로 값을 삽입
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
    if (qName) elementName = qName;
	
	TreeNode *leaf = [TreeNode treeNode];
	leaf.parent = [stack lastObject];
	[(NSMutableArray *)[[stack lastObject] children] addObject:leaf];
	
	leaf.key = [NSString stringWithString:elementName];
	leaf.leafvalue = nil;
	leaf.children = [NSMutableArray array];
	
	[stack addObject:leaf];
}

//Element의 끝
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
	[stack removeLastObject];
}

//Element의 스트링 값을 leafvalue에 저장
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
	if (![[stack lastObject] leafvalue])
	{
		[[stack lastObject] setLeafvalue:[NSString stringWithString:string]];
		return;
	}
	[[stack lastObject] setLeafvalue:[NSString stringWithFormat:@"%@%@", [[stack lastObject] leafvalue], string]];
}

@end